package com.sinogrand.elevator.ui.screens

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Search
import androidx.compose.material.icons.filled.Clear
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.platform.LocalContext
import com.sinogrand.elevator.data.models.ApprovalRecordItem
import com.sinogrand.elevator.network.NetworkClient
import com.sinogrand.elevator.utils.LogTags
import com.google.gson.JsonObject
import kotlinx.coroutines.launch
import kotlinx.coroutines.delay
import android.util.Log

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun MyApprovalScreen(
    onNavigateBack: () -> Unit,
    onNavigateToApproval: (Int) -> Unit = {}
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    
    // Tab状态管理
    var selectedTab by rememberSaveable { mutableStateOf(0) }
    val tabs = listOf("未处理", "已处理")
    
    // 状态管理
    var approvalList by remember { mutableStateOf<List<ApprovalRecordItem>>(emptyList()) }
    var isLoading by remember { mutableStateOf(false) }
    var isRefreshing by remember { mutableStateOf(false) }
    var isLoadingMore by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf<String?>(null) }
    var currentPage by remember { mutableStateOf(1) }
    var hasMoreData by remember { mutableStateOf(true) }
    var searchQuery by remember { mutableStateOf("") }
    var isSearching by remember { mutableStateOf(false) }
    
    val listState = rememberLazyListState()
    
    // API服务
    val apiService = remember { NetworkClient.getApiService(context) }
    
    // 加载数据函数
    suspend fun loadApprovalData(page: Int = 1, isRefresh: Boolean = false, searchTitle: String? = null) {
        try {
            Log.d(LogTags.MAIN_ACTIVITY, "开始加载审批记录数据，页码: $page, 状态: ${selectedTab + 1}, 搜索: $searchTitle")
            
            if (isRefresh) {
                isRefreshing = true
            } else if (page == 1) {
                isLoading = true
            } else {
                isLoadingMore = true
            }
            
            errorMessage = null
            
            val request = JsonObject().apply {
                addProperty("status", selectedTab + 1) // 1.未处理, 2.已处理
                addProperty("page", page)
                addProperty("size", 20)
                if (!searchTitle.isNullOrEmpty()) {
                    addProperty("title", searchTitle)
                }
            }
            
            val apiResponse = apiService.getApprovalRecordList(request)
            
            if (apiResponse.code == 0 && apiResponse.data != null) {
                val newList = apiResponse.data.list
                val pageInfo = apiResponse.data.page_info
                
                Log.i(LogTags.MAIN_ACTIVITY, "📋 获取到审批记录数据: ${newList.size}条")
                
                if (isRefresh || page == 1) {
                    approvalList = newList
                } else {
                    approvalList = approvalList + newList
                }
                
                hasMoreData = page < pageInfo.total
                currentPage = page
                
                Log.i(LogTags.MAIN_ACTIVITY, "✅ 成功加载审批记录数据: ${approvalList.size}条")
            } else {
                Log.e(LogTags.MAIN_ACTIVITY, "❌ 加载审批记录数据失败: ${apiResponse.msg}")
                errorMessage = apiResponse.msg
            }
        } catch (e: Exception) {
            Log.e(LogTags.MAIN_ACTIVITY, "💥 加载审批记录数据异常: ${e.message}", e)
            errorMessage = "加载失败: ${e.message}"
        } finally {
            isLoading = false
            isRefreshing = false
            isLoadingMore = false
        }
    }
    
    // 下拉刷新
    fun onRefresh() {
        scope.launch {
            loadApprovalData(isRefresh = true, searchTitle = if (searchQuery.isNotEmpty()) searchQuery else null)
        }
    }
    
    // 加载更多
    fun loadMore() {
        if (!isLoadingMore && hasMoreData) {
            scope.launch {
                loadApprovalData(currentPage + 1, searchTitle = if (searchQuery.isNotEmpty()) searchQuery else null)
            }
        }
    }
    
    // 搜索功能
    fun handleSearch(query: String) {
        searchQuery = query
        isSearching = true
        
        scope.launch {
            delay(300) // 防抖延迟
            loadApprovalData(searchTitle = if (query.isNotEmpty()) query else null)
            isSearching = false
        }
    }
    
    // Tab切换
    fun onTabChanged(tabIndex: Int) {
        selectedTab = tabIndex
        // 不需要手动调用loadApprovalData，LaunchedEffect会自动处理
    }
    
    // 清除搜索
    fun handleClearSearch() {
        searchQuery = ""
        handleSearch("")
    }
    
    // 初始加载和Tab切换时重新加载
    LaunchedEffect(selectedTab) {
        loadApprovalData(searchTitle = if (searchQuery.isNotEmpty()) searchQuery else null)
    }
    
    Scaffold(
        topBar = {
            TopAppBar(
                title = {
                    Text(
                        text = "我的审批",
                        fontSize = 18.sp,
                        fontWeight = FontWeight.Bold,
                        color = Color(0xFF1F2937)
                    )
                },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(
                            imageVector = Icons.AutoMirrored.Filled.ArrowBack,
                            contentDescription = "返回"
                        )
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color.White,
                    titleContentColor = Color(0xFF1F2937),
                    navigationIconContentColor = Color(0xFF1F2937)
                ),
                modifier = Modifier.shadow(2.dp)
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .background(
                    Brush.verticalGradient(
                        colors = listOf(
                            Color(0xFFF8FAFC),
                            Color(0xFFF1F5F9)
                        )
                    )
                )
                .padding(paddingValues)
        ) {
            // Tab选择器
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(start = 16.dp, top = 16.dp, end = 16.dp, bottom = 8.dp),
                colors = CardDefaults.cardColors(
                    containerColor = Color.White
                ),
                elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                shape = RoundedCornerShape(12.dp)
            ) {
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(4.dp),
                    horizontalArrangement = Arrangement.SpaceEvenly
                ) {
                    tabs.forEachIndexed { index, tabTitle ->
                        ApprovalTabButton(
                            text = tabTitle,
                            isSelected = selectedTab == index,
                            onClick = { onTabChanged(index) },
                            modifier = Modifier.weight(1f)
                        )
                    }
                }
            }
            
            // 搜索框
            ApprovalSearchBar(
                query = searchQuery,
                onQueryChange = { searchQuery = it },
                onSearch = { handleSearch(searchQuery) },
                onClear = { handleClearSearch() },
                placeholder = "搜索标题...",
                isSearching = isSearching,
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
                    .height(48.dp)
            )
            
            // 列表内容
            Box(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
            ) {
                when {
                    isLoading && approvalList.isEmpty() -> {
                        // 初始加载状态
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                CircularProgressIndicator(
                                    color = Color(0xFF3B82F6)
                                )
                                Spacer(modifier = Modifier.height(16.dp))
                                Text(
                                    text = "加载中...",
                                    fontSize = 16.sp,
                                    color = Color(0xFF6B7280)
                                )
                            }
                        }
                    }
                    
                    errorMessage != null && approvalList.isEmpty() -> {
                        // 错误状态
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = "加载失败",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = Color(0xFFDC2626)
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(
                                    text = errorMessage ?: "未知错误",
                                    fontSize = 14.sp,
                                    color = Color(0xFF6B7280)
                                )
                                Spacer(modifier = Modifier.height(16.dp))
                                Button(
                                    onClick = {
                                        errorMessage = null
                                        scope.launch {
                                            loadApprovalData(searchTitle = if (searchQuery.isNotEmpty()) searchQuery else null)
                                        }
                                    }
                                ) {
                                    Text("重试")
                                }
                            }
                        }
                    }
                    
                    approvalList.isEmpty() -> {
                        // 空状态
                        Box(
                            modifier = Modifier.fillMaxSize(),
                            contentAlignment = Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = Alignment.CenterHorizontally
                            ) {
                                Text(
                                    text = "暂无${tabs[selectedTab]}记录",
                                    fontSize = 18.sp,
                                    fontWeight = FontWeight.Medium,
                                    color = Color(0xFF6B7280)
                                )
                                Spacer(modifier = Modifier.height(8.dp))
                                Text(
                                    text = "您还没有任何${tabs[selectedTab]}的审批记录",
                                    fontSize = 14.sp,
                                    color = Color(0xFF9CA3AF)
                                )
                            }
                        }
                    }
                    
                    else -> {
                        // 列表内容
                        LazyColumn(
                            state = listState,
                            modifier = Modifier.fillMaxSize(),
                            contentPadding = PaddingValues(16.dp),
                            verticalArrangement = Arrangement.spacedBy(12.dp)
                        ) {
                            items(
                                count = approvalList.size,
                                key = { index -> approvalList[index].id }
                            ) { index ->
                                val approval = approvalList[index]
                                ApprovalRecordListItem(
                                    approval = approval,
                                    onClick = {
                                        Log.d(LogTags.MAIN_ACTIVITY, "点击审批记录: formId=${approval.form_id}")
                                        onNavigateToApproval(approval.form_id)
                                    }
                                )
                            }
                            
                            // 加载更多指示器
                            if (isLoadingMore && approvalList.isNotEmpty()) {
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        CircularProgressIndicator(
                                            modifier = Modifier.size(24.dp),
                                            color = Color(0xFF3B82F6)
                                        )
                                    }
                                }
                            }
                            
                            // 没有更多数据提示
                            if (!hasMoreData && approvalList.isNotEmpty()) {
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(16.dp),
                                        contentAlignment = Alignment.Center
                                    ) {
                                        Text(
                                            text = "没有更多数据了",
                                            fontSize = 14.sp,
                                            color = Color(0xFF9CA3AF)
                                        )
                                    }
                                }
                            }
                        }
                    }
                }
                
                // 下拉刷新指示器
                if (isRefreshing) {
                    Box(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 16.dp),
                        contentAlignment = Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            modifier = Modifier.size(24.dp),
                            color = Color(0xFF3B82F6)
                        )
                    }
                }
            }
        }
    }
}

@Composable
fun ApprovalSearchBar(
    query: String,
    onQueryChange: (String) -> Unit,
    onSearch: () -> Unit,
    onClear: () -> Unit = {},
    placeholder: String = "搜索",
    isSearching: Boolean = false,
    modifier: Modifier = Modifier
) {
    Card(
        modifier = modifier.fillMaxWidth(),
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 10.dp),
            verticalAlignment = Alignment.CenterVertically
        ) {
            Icon(
                imageVector = Icons.Default.Search,
                contentDescription = null,
                tint = Color(0xFF6B7280),
                modifier = Modifier.size(24.dp)
            )
            
            Spacer(modifier = Modifier.width(6.dp))
            
            val keyboardController = LocalSoftwareKeyboardController.current
            
            BasicTextField(
                value = query,
                onValueChange = onQueryChange,
                modifier = Modifier
                    .weight(1f)
                    .height(48.dp),
                textStyle = TextStyle(
                    fontSize = 14.sp,
                    color = Color(0xFF1F2937)
                ),
                decorationBox = { innerTextField ->
                    Box(
                        modifier = Modifier.fillMaxWidth(),
                        contentAlignment = Alignment.CenterStart
                    ) {
                        if (query.isEmpty()) {
                            Text(
                                text = placeholder,
                                color = Color(0xFF9CA3AF),
                                fontSize = 14.sp,
                                lineHeight = 10.sp
                            )
                        }
                        innerTextField()
                    }
                },
                singleLine = true,
                keyboardOptions = KeyboardOptions(
                    imeAction = ImeAction.Search
                ),
                keyboardActions = KeyboardActions(
                    onSearch = {
                        onSearch()
                        keyboardController?.hide()
                    }
                )
            )
            
            if (isSearching) {
                Box(
                    modifier = Modifier.size(28.dp),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(16.dp),
                        strokeWidth = 2.dp,
                        color = Color(0xFF3B82F6)
                    )
                }
            } else if (query.isNotEmpty()) {
                IconButton(
                    onClick = onClear,
                    modifier = Modifier.size(28.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Clear,
                        contentDescription = "清除搜索",
                        tint = Color(0xFF6B7280),
                        modifier = Modifier.size(14.dp)
                    )
                }
            }
        }
    }
}

@Composable
fun ApprovalTabButton(
    text: String,
    isSelected: Boolean,
    onClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    if (isSelected) {
        Card(
            modifier = modifier
                .padding(2.dp)
                .clip(RoundedCornerShape(8.dp)),
            colors = CardDefaults.cardColors(
                containerColor = Color(0xFF3B82F6)
            ),
            elevation = CardDefaults.cardElevation(defaultElevation = 2.dp)
        ) {
            TextButton(
                onClick = onClick,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(
                    text = text,
                    color = Color.White,
                    fontSize = 14.sp,
                    fontWeight = FontWeight.Bold
                )
            }
        }
    } else {
        TextButton(
            onClick = onClick,
            modifier = modifier.fillMaxWidth()
        ) {
            Text(
                text = text,
                color = Color(0xFF6B7280),
                fontSize = 14.sp,
                fontWeight = FontWeight.Medium
            )
        }
    }
}

@Composable
fun ApprovalRecordListItem(
    approval: ApprovalRecordItem,
    onClick: () -> Unit
) {
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .clickable { onClick() },
        colors = CardDefaults.cardColors(
            containerColor = Color.White
        ),
        elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
        shape = RoundedCornerShape(12.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            // 标题
            Text(
                text = approval.title,
                fontSize = 16.sp,
                fontWeight = FontWeight.Medium,
                color = Color(0xFF1F2937),
                maxLines = 2,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(8.dp))
            
            // 模板名称
            Text(
                text = approval.template_name,
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
            
            Spacer(modifier = Modifier.height(4.dp))
            
            // 项目名称
            Text(
                text = approval.project_name,
                fontSize = 14.sp,
                color = Color(0xFF6B7280),
                maxLines = 1,
                overflow = TextOverflow.Ellipsis
            )
        }
    }
}